﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.GISClient;
using System.Threading;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Server;

namespace ClientApplication
{
    public partial class ServerConn : Form
    {
        //
        private GisServer gisServer = new GisServer();
        private ProcessBarWin myProcessBar = null;
       // private GISServerMng myGisServerMng = null;
        private bool connResult = false;
        private bool processBarComplete = false;
       // private List<IAGSServerObjectName> pList;
        private string serverUrl;
        private string username;
        private string password;
        private IAGSServerConnection customerConn = null;

        public IAGSServerConnection CustomerConn
        {
            get { return customerConn; }
            set { customerConn = value; }
        }
        private IServerObjectAdmin serverAdmin = null;

        public IServerObjectAdmin ServerAdmin
        {
            get { return serverAdmin; }
            set { serverAdmin = value; }
        }



        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public ServerConn(string url, string username, string password)
        {
            this.serverUrl = url;
            this.username = username;
            this.password = password;
            InitializeComponent();
        }
        public ServerConn(GisServer gis) 
        {
            this.gisServer = gis;
            InitializeComponent();
        }
        /// <summary>
        /// 连接Button事件处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_conn_Click(object sender, EventArgs e)
        {
            if (textBox_server.Text.Trim() != String.Empty)
            {
                //myGisServerMng = new GISServerMng(textBox_server.Text, Username,Password);
                //PList = myGisServerMng.ConnectUserAGS();
                ////ThreadStart threadStart = new ThreadStart(mng.ConnectUserAGS);//通过ThreadStart委托告诉子线程讲执行什么方法
                ////PList = mng.ConnectUserAGS();
                // Thread thdSub1 = new Thread(new ThreadStart(ProBarThreadFun));
                //Thread thdSub2 = new Thread(new ThreadStart(SerObjThreadFun));
                //Thread thdSub3 = new Thread(new ThreadStart(ChangeBtnEnable));
                //thdSub1.Start();
                //thdSub2.Start();
                //启动线程用来监控连接成功后修改Button状态
                //this.backgroundWorker_changebtn.RunWorkerAsync();
                //启动线程用来创建进度条
                //this.backgroundWorker_probar.WorkerReportsProgress = true;
                //this.backgroundWorker_probar.RunWorkerAsync();
                //myProcessBar = new ProcessBarWin();
                //this.backgroundWorker_probar.WorkerReportsProgress = true;
                //this.backgroundWorker_probar.RunWorkerAsync();
                //myProcessBar.ShowDialog();
                //启动线程进行连接GISServer
                //thdSub3.Start();
                //if (!connResult)
                //{
                //    MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //}
                //else
                //{
                //    MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    btn_conn.Enabled = false;
                //    btn_ok.Enabled = true;
                //}

                //启动GISServer连接子线程
                //myGisServerMng = new GISServerMng(textBox_server.Text, Username, Password);
                backgroundWorker_conn.RunWorkerAsync();

                //启动进度条子线程
                myProcessBar = new ProcessBarWin();
                myProcessBar.Text = "正在连接请耐心等待...";
                //backgroundWorker_probar.WorkerReportsProgress = true;
                //backgroundWorker_probar.RunWorkerAsync();
                //设置进度条线程支持异步取消
                //backgroundWorker_probar.WorkerSupportsCancellation = true;
                myProcessBar.ShowDialog();

                //启动button修改监听子线程
                backgroundWorker_changebtn.RunWorkerAsync();

            }
            else
            {
                MessageBox.Show("请输入GISServer的地址", "服务器地址不合法", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #region 进度条子线程控制
        //private void countTheTime()
        //{
        //    int initialValue = 100;
        //    for (int count = 0; count < initialValue; count = count + 1)
        //    {
        //        Thread.Sleep(300);
        //        //backgroundWorker_probar.ReportProgress(count);
        //    }
        //}

        //private void backgroundWorker_probar_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    countTheTime();
        //}

        private void backgroundWorker_probar_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (!backgroundWorker_probar.CancellationPending)
            {
                //当进度条线程没有被请求取消时才计算进度条增长值
                myProcessBar.Increase(e.ProgressPercentage);
            }
            //myProcessBar.ProgressValue = e.ProgressPercentage;
        }

        //private void backgroundWorker_probar_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    //关闭进度条子窗体
        //    myProcessBar.Close();
        //    // MessageBox.Show("进度条完成");
        //    //释放进度条窗体引用
        //    myProcessBar = null;

        //    //设置进度条完成标记变量为True
        //    processBarComplete = true;
        //}
        #endregion


        #region GISServer连接线程
        private void backgroundWorker_conn_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(1000);
            backgroundWorker_probar.ReportProgress(10);
            //获取Custom连接对象
            CustomerConn = this.ConnectUserAGS(this.gisServer.GisUrl, this.gisServer.GisUsername, this.gisServer.GisPassword);
            backgroundWorker_probar.ReportProgress(30);
            //获取Admin连接对象
            ServerAdmin = this.GetObjAdmin(this.gisServer.GisUrl, this.gisServer.GisUsername, this.gisServer.GisPassword);
            backgroundWorker_probar.ReportProgress(60);
            Thread.Sleep(1000);
            //MessageBox.Show("connect dowork ok");
        }

        private void backgroundWorker_conn_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //MessageBox.Show("start conn complete");
            try
            {
                IAGSEnumServerObjectName pServerObjectNames = customerConn.ServerObjectNames;
                pServerObjectNames.Reset();
                Thread.Sleep(1000);
                backgroundWorker_probar.ReportProgress(90);
                IAGSServerObjectName agsServerObjectName = pServerObjectNames.Next();
                //根据agsServerObjectName判断连接是否成功，并更新连接成功标记
                if ((agsServerObjectName != null) && (ServerAdmin != null))
                {
                    //MessageBox.Show("连接成功");

                    connResult = true;
                    Thread.Sleep(3000);
                    backgroundWorker_probar.ReportProgress(100);
                    Thread.Sleep(500);
                    //关闭进度条子窗体
                    myProcessBar.Close();
                    // MessageBox.Show("进度条完成");
                    //释放进度条窗体引用
                    myProcessBar = null;

                    //设置进度条完成标记变量为True
                    processBarComplete = true;

                }
                else
                {
                    MessageBox.Show("请重新连接GISServer", "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception)
            {

                MessageBox.Show("请检查GISServer地址，重新连接GISServer", "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                myProcessBar.Close();
                myProcessBar = null;
            }
            
        }
        #endregion


        #region button状态修改监听线程
        private void backgroundWorker_changebtn_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //MessageBox.Show("监听完成");
            MessageBox.Show("连接成功", "连接GISServer成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.btn_conn.Enabled = false;

            this.btn_ok.Enabled = true;
        }

        private void backgroundWorker_changebtn_DoWork(object sender, DoWorkEventArgs e)
        {
            bool tag = true;
            while (tag)
            {
                if (connResult && processBarComplete)
                {
                    tag = false;
                }
            }
        }

        #endregion

        #region 建立custom状态的连接
        private IAGSServerConnection ConnectUserAGS(string host, string username, string password)
        {
            IAGSServerConnection pConnection = null;
            try
            {

                IPropertySet propertySet = new PropertySetClass();
                propertySet.SetProperty("url", host);
                propertySet.SetProperty("ConnectionMode", esriAGSConnectionMode.esriAGSConnectionModeConsumer);
                //propertySet.SetProperty("ServerType", esriAGSServerType.esriAGSServerTypeDiscovery);
                propertySet.SetProperty("user", username);
                propertySet.SetProperty("password", password);
                //propertySet.SetProperty("ALLOWINSECURETOKENURL", true); 

                //打开连接

                // IAGSServerConnectionFactory pFactory = new AGSServerConnectionFactory();
                //Type factoryType = Type.GetTypeFromProgID(
                //    "esriGISClient.AGSServerConnectionFactory");
                //IAGSServerConnectionFactory agsFactory = (IAGSServerConnectionFactory)
                //    Activator.CreateInstance(factoryType);


                IAGSServerConnectionName3 pConnectName = new AGSServerConnectionNameClass() as IAGSServerConnectionName3;//10.1新增接口
                pConnectName.ConnectionProperties = propertySet;

                pConnection = ((IName)pConnectName).Open() as IAGSServerConnection;

                //IAGSServerConnection pConnection = pFactory.Open(propertySet, 0);
                //IAGSEnumServerObjectName pServerObjectNames = pConnection.ServerObjectNames;
                //pServerObjectNames.Reset();

                //IAGSServerObjectName agsServerObjectName = pServerObjectNames.Next();
                //while (agsServerObjectName != null)
                //{
                //    pList.Add(agsServerObjectName);
                //    agsServerObjectName = pServerObjectNames.Next();
                //}



            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
            //return pList;
            return pConnection;

        }
        #endregion

        #region 建立Admin状态的连接
        private IServerObjectAdmin GetObjAdmin(string host, string username, string password)
        {
            try
            {
                IPropertySet propertySet = new PropertySetClass();
                propertySet.SetProperty("url", host);
                propertySet.SetProperty("ConnectionMode", esriAGSConnectionMode.esriAGSConnectionModeAdmin);
                propertySet.SetProperty("ServerType", esriAGSServerType.esriAGSServerTypeDiscovery);
                propertySet.SetProperty("user", username);
                propertySet.SetProperty("password", password);
                propertySet.SetProperty("ALLOWINSECURETOKENURL", true); //设置为false会弹出一个警告对话框

                IAGSServerConnectionName3 pConnectName = new AGSServerConnectionNameClass() as IAGSServerConnectionName3;//10.1新增接口
                pConnectName.ConnectionProperties = propertySet;

                IAGSServerConnectionAdmin pAGSAdmin = ((IName)pConnectName).Open() as IAGSServerConnectionAdmin;


                return pAGSAdmin.ServerObjectAdmin;
            }
            catch (Exception exc)
            {
                throw new ApplicationException(exc.Message);
            }
        }
        #endregion

        //窗体加载处理函数
        private void ServerConn_Load(object sender, EventArgs e)
        {
            textBox_server.Text = this.gisServer.GisUrl;
            btn_ok.DialogResult = DialogResult.OK;
            btn_cancle.DialogResult = DialogResult.Cancel;
            btn_ok.Enabled = false;
        }


    }
}
